import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import mall from "@src/store/mall";
import { getNearStore, getStoreList, getDispatchWay, getStoreDetail } from "@mall/api/store";
import router from "@src/router";
import { batchDeleteItem, updateItemNum } from "@mall/api/shopCart";
import { preOrderFun } from "@mall/api/order";

const { getShopCartList } = require("@mall/api/shopCart");
Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: mall,
    fields: ['curLocation', 'storeId'],
    actions: ['initLocation', 'setAddress', 'setStoreId']
  }],
  properties: {},
  data: {
    loading: true,
    defaultStoreId: 0,
    cartList: [],
    firstShow: true,
    invalidItems: [],
    fileBaseUrl: null,
    checkedAll: false,
    deliveryType: null,
    storesShow: false,
    storeList: [],
    dispatchShow: false,
    selectedCartGoods: [],
    priceCount: 0,
    showNum: 0,
    timeoutId: null,
    isOpenDispatch: true,
    storeInfo: {},
    filterList: [{
      id: "sort",
      title: "距离远近",
      type: "single",
      data: [
        { id: 1, title: "距离从近到远" },
        { id: 2, title: "距离从远到近" }
      ]
    }, {
      id: "buyWay",
      title: "购买方式",
      type: "single",
      data: [
        { id: 0, title: "外卖配送", str: 'LOCAL' },
        { id: 1, title: "到店自提", str: 'SELF_PICKUP' },
        { id: 2, title: "快递邮寄", str: 'EXPRESS' }
      ]
    }],
    dispatchWayDescribe: [
      {
        title: '外卖配送',
        describe: '支持配送',
        image: '../../../static/icon/take_out.png',
        status: 2,
        str: 'LOCAL',
        disabled: false,
        isShow: false,
        goods: []
      },
      {
        title: '到店自提',
        describe: '支持自提',
        image: '../../../static/icon/store.png',
        status: 2,
        str: 'SELF_PICKUP',
        disabled: false,
        isShow: false,
        goods: []
      },
      {
        title: '快递邮寄',
        describe: '支持邮寄',
        image: '../../../static/icon/fast_mail.png',
        status: 2,
        str: 'EXPRESS',
        disabled: false,
        isShow: false,
        goods: []
      }
    ]
  },
  observers: {
    curLocation(curLocation) {
      if (!curLocation) return
      const { longitude, latitude } = curLocation
      getStoreList({ latitude, longitude })
        .then(res => {
          this.setData({ storeList: res.data })
        })
    },
    storeId(storeId) {
      if (!storeId) return
      this.getStoreInfo()
    }
  },
  methods: {
    getStoreInfo() {
      getStoreDetail({ storeId: this.data.storeId })
        .then(res => {
          const { supplyLocal, supplySelfPickup, supplyExpress } = res.data.delivery
          if (!supplyLocal && !supplySelfPickup && !supplyExpress) {
            this.setData({ isOpenDispatch: false, storeInfo: res.data })
            return
          }
          let dispatchWayDescribe = this.data.dispatchWayDescribe
          dispatchWayDescribe[0].isShow = false
          dispatchWayDescribe[1].isShow = false
          dispatchWayDescribe[2].isShow = false
          supplyLocal && (dispatchWayDescribe[0].isShow = true)
          supplySelfPickup && (dispatchWayDescribe[1].isShow = true)
          supplyExpress && (dispatchWayDescribe[2].isShow = true)
          this.setData({ dispatchWayDescribe, storeInfo: res.data })
        })
    },
    dispatchHide() {
      this.setData({ dispatchShow: false })
    },
    back() {
      wx.navigateBack()
    },
    onLoad() {
      this.setData({ fileBaseUrl: getApp().globalData.extConfig.fileBaseUrl })
    },
    onShow() {
      this.setData({
        storesShow: false,
        dispatchShow: false,
        checkedAll: false,
        selectedCartGoods: [],
        priceCount: 0
      })
      if (this.data.firstShow) {
        this.setData({
          firstShow: false
        })
        return;
      }
      if (this.data.storeId) {
        this.fetchData();
      }
    },
    onLogin() {
      this.updateStoreBindings();
      if (this.data.storeId) {
        this.fetchData();
        return;
      }
      if (!this.data.curLocation) {
        // 先拉取一个默认门店
        this.fetchDefaultStore().then(() => {
          this.fetchData();
        });
      }
      // 定位, 并刷新购物车
      this.initLocation().then(res => {
        let params = { latitude: res.latitude, longitude: res.longitude }
        this.fetchNearStore(params).then(res => {
          this.fetchData();
        })
      }).catch(error => {
        this.fetchNearStore({}).then(res => {
          console.log(res)
          this.fetchData();
        })
      });

    },
    getStoreList(e) {
      const { detail } = e
      console.log(detail)
      if (detail[0] == 0 && detail[1].id == 1) {
        let storeList = this.data.storeList
        storeList.sort((a, b) => a.distance - b.distance)
        this.setData({ storeList })
      } else if (detail[0] == 0 && detail[1].id == 2) {
        let storeList = this.data.storeList
        storeList.sort((a, b) => b.distance - a.distance)
        this.setData({ storeList })
      }

      if (detail[0] == 1 && detail[1].str) {
        getStoreList({
          type: detail[1].str,
          latitude: this.data.curLocation.latitude,
          longitude: this.data.curLocation.longitude
        })
          .then(res => {
            this.setData({ storeList: res.data })
          })
      }
    },
    selectedDispatchWay({ currentTarget }) {
      const { dispatch } = currentTarget.dataset
      if (dispatch.disabled) return
      this.setData({ deliveryType: dispatch.str })
      this.handlePreOrder(dispatch.goods)
    },
    getDispatchWay() {
      const { supplyExpress, supplyLocal, supplySelfPickup } = this.data.storeInfo.delivery
      if (!supplyExpress && !supplyLocal && !supplySelfPickup) {
        wx.showToast({
          title: '当前门店未配置任何配送方式，暂时无法下单',
          icon: 'none'
        })
        return
      }

      if (!this.data.selectedCartGoods.length || this.data.cartList[0].errorCode !== 0) return

      let params = {
        items: this.data.selectedCartGoods,
        storeId: this.data.cartList[0].storeId,
        subType: '',
        source: 0
      }
      getDispatchWay(params)
        .then(res => {
          if (res.code !== 0) return
          this.setData({ dispatchShow: true })
          let dispatchWayDescribe = this.data.dispatchWayDescribe
          const {
            expressItems,
            localItems,
            selfPickupItems,
            supplyExpress,
            supplyLocal,
            supplySelfPickup
          } = res.data
          dispatchWayDescribe[0].disabled = !!!supplyLocal
          dispatchWayDescribe[0].status = supplyLocal
          dispatchWayDescribe[0].goods = (localItems || [])
          dispatchWayDescribe[1].disabled = !!!supplySelfPickup
          dispatchWayDescribe[1].status = supplySelfPickup
          dispatchWayDescribe[1].goods = (selfPickupItems || [])
          dispatchWayDescribe[2].disabled = !!!supplyExpress
          dispatchWayDescribe[2].status = supplyExpress
          dispatchWayDescribe[2].goods = (expressItems || [])
          this.setData({ dispatchWayDescribe, dispatchGoods: res.data })
        })

    },

    openSwitchStore() {
      this.setData({ storesShow: true })
    },
    enterStore({ target }) {
      const { store } = target.dataset
      if (!store.disabled) {
        this.setStoreId(store.storeId)
        this.updateStoreBindings();
        this.fetchData()
        this.setData({
          storesShow: false,
          storesShow: false,
          dispatchShow: false,
          checkedAll: false,
          selectedCartGoods: [],
          priceCount: 0
        })
      }
    },
    selectedAll(e) {
      const { value } = e.detail
      this.data.cartList[0].items.forEach(item => { item.checked = !!value.length })
      if (value.length) {
        const { items } = this.data.cartList[0]
        this.setData({ selectedCartGoods: items })
      } else {
        this.setData({ selectedCartGoods: [] })
      }
      this.setData({ cartList: this.data.cartList })
      this.PriceCount()
    },
    selectedChange(e) {

      const { value } = e.detail
      console.log(value)
      let selectedItems = []
      this.data.cartList[0].items.forEach(item => {
        item.checked = value.includes(JSON.stringify(item.cartItemId))
        if (value.includes(JSON.stringify(item.cartItemId))) {
          selectedItems.push(item)
        }
      })
      this.setData({
        checkedAll: value.length === this.data.cartList[0].items.length,
        cartList: this.data.cartList,
        selectedCartGoods: selectedItems
      })

      this.PriceCount()

    },
    fetchData() {
      let storeId = this.data.storeId;
      if (storeId == null) {
        storeId = this.data.defaultStoreId;
      }
      let data = {
        storeId: storeId,
        cartType: 0,
        type: 'NO_CHOICE'
      }
      getShopCartList(data).then(res => {
        let cartList = res.data;
        let selectedCartGoods = []
        let invalidItems = [];
        for (let i = 0; i < cartList.length; i++) {
          let cart = cartList[i];
          if (cart.invalidItems && cart.invalidItems.length > 0) {
            invalidItems = invalidItems.concat(cart.invalidItems)
          }
        }
        if (cartList.length) {
          cartList[0].items.forEach(item => { item.checked = false })
          cartList[0].items.forEach(item => {
            this.data.selectedCartGoods.forEach((cItem, index) => {
              if (item.cartItemId === cItem.cartItemId) {
                item.checked = true
              }
            })
          })
          cartList[0].items.forEach(item => {
            item.skuInfo = JSON.parse(item.skuInfo).join(',')
            item.checked && selectedCartGoods.push(item)
          })
        }

        this.setData({ cartList, invalidItems, selectedCartGoods, loading: false })
        this.PriceCount()
      })

    },
    updataFetchData: function () {
      this.fetchData()
    },
    onPullDownRefresh: function () {
      if (this.data.storeId) {
        this.fetchData();
      }
      wx.stopPullDownRefresh();
    },
    fetchNearStore(params) {
      return getNearStore(params).then(res => {
        this.setStoreId(res.data.storeId)
        this.updateStoreBindings();
        return res;
      })
    },
    fetchDefaultStore() {
      return getNearStore({}).then(res => {
        this.setData({ defaultStoreId: res.data.storeId })
        return res;
      })
    },
    goGoodsList() {
      router.push({ name: "mall/goods-list", params: { storeId: this.data.storeId } })
    },
    handleUpdate() {
      this.fetchData();
    },
    PriceCount() {
      const count = this.data.selectedCartGoods.reduce((prev, cur) => prev + (cur.price * cur.num), 0)
      this.setData({ priceCount: count.toFixed(2) })
    },
    handleClearCartItems() {
      let cartItemDel = [];
      this.data.cartList[0].items.forEach(item => {
        if (item.checked) {
          let temp = {
            cartItemId: item.cartItemId,
            goodsId: item.goodsId,
            skuId: item.skuId,
            storeId: item.storeId,
          }
          cartItemDel.push(temp);
        }
      })
      if (!cartItemDel.length) {
        wx.showToast({
          title: '请勾选需要删除的商品',
          icon: 'none'
        })
        return
      }
      wx.showModal({
        title: "温馨提示", content: "是否删除所选商品?",
        showCancel: true,
        success: (res) => {
          if (res.confirm) {


            batchDeleteItem(cartItemDel).then(res => {
              this.setData({ selectedCartGoods: [] })
              this.fetchData()
            })
          }
        }
      });


    },
    handleAdd({ target }) {
      const { good, isadd = true } = target.dataset
      let showNum = this.data.showNum
      if (!isadd && good.num <= 1) {
        const { cartItemId, storeId } = good
        batchDeleteItem([{ cartItemId, storeId }]).then(res => {
          this.setData({ invalidItems: [] })
          this.fetchData()
        })
        return
      }
      if (good.limitNum !== 0 && showNum + 1 > good.limitNum) {
        wx.showToast({ title: "超出最大购买数量", icon: "none", duration: 2000 });
        return;
      }
      if (good.stockNum !== 0 && showNum + 1 > good.stockNum) {
        wx.showToast({ title: "商品库存不足", icon: "none", duration: 2000 });
        return;
      }
      if (isadd) {
        showNum = showNum + 1
      } else {
        showNum = showNum - 1
      }

      this.setData({ showNum: showNum });
      // 限流
      this.throttleEvent(good, showNum);
    },
    throttleEvent(good, showNum) {
      let timeoutId = this.data.timeoutId
      if (timeoutId) {
        this.setData({ timeoutId: null })
        clearTimeout(timeoutId);
      }
      timeoutId = setTimeout(() => {
        this.updateItemNum(good, showNum)
      }, 100)
      this.setData({ timeoutId: timeoutId })
    },
    updateItemNum(good, showNum) {
      let params = {
        cartItemId: good.cartItemId,
        goodsId: good.goodsId,
        num: (showNum + good.num),
        skuId: good.skuId,
        storeId: this.data.cartList[0].storeId
      }
      this.setData({ showNum: 0 })
      if (params.num <= 0) return
      updateItemNum(params)
        .then(res => {
          this.fetchData()
        })
    },
    handlePreOrder(goods = []) {
      let selectCartList = goods
      if (selectCartList.length === 0) {
        return;
      }
      let orderPreForm = {
        items: [],
        source: 0,
        storeId: this.data.storeId,
        type: this.data.deliveryType
      };
      selectCartList.forEach(item => {
        orderPreForm.items.push(item)
      })
      wx.showLoading({ title: "下单中...", mark: true });
      let deliveryType = this.data.deliveryType
      preOrderFun(orderPreForm).then(res => {
        wx.hideLoading();
        if (res.code === 0) {
          router.push({
            name: 'mall/submit-order',
            params: { preNo: res.data.preNo, deliveryType: deliveryType, storeNo: this.data.storeInfo.storeNo },
            success: (res) => {
              if (deliveryType === 'LOCAL') {
                setTimeout(() => {
                  res.eventChannel.emit('showSelectDelivery');
                }, 300)
              }
            }
          })
        }
      }).catch((res) => {
        if (res.data.data.invalidItems.length > 0) {
          wx.showToast({
            icon: 'none',
            title: res.data.data.invalidItems[0].title + res.data.data.invalidItems[0].errorMsg,
          })
        }
      })
    },

    handleClearInvalidItems() {
      if (this.data.invalidItems.length > 0) {
        wx.showModal({
          title: "温馨提示", content: "是否清除失效商品?",
          showCancel: true,
          success: (res) => {
            if (res.confirm) {
              let cartItemDel = [];
              this.data.invalidItems.forEach(item => {
                let temp = {
                  cartItemId: item.cartItemId,
                  goodsId: item.goodsId,
                  skuId: item.skuId,
                  storeId: item.storeId,
                }
                cartItemDel.push(temp);
              })
              batchDeleteItem(cartItemDel).then(res => {
                this.setData({ invalidItems: [] })
                this.fetchData()
              })
            }
          }
        });
      }
    }
  }
});